package com.yanqu.road.api.test;

import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.utils.executor.GeneralThreadFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * wmm
 * 2023/2/5
 */
public class JobClientHandler extends SimpleChannelInboundHandler {

    private static final Logger logger = LogManager.getLogger(JobClientHandler.class.getName());

    private static ExecutorService testCmdExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 4, new GeneralThreadFactory("test-server-cmd"));

    private long jobId;

    public void setJobId(long jobId) {
        this.jobId = jobId;
    }

    public JobClientHandler(long jobId) {
        this.jobId = jobId;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof YanQuMessage){
            testCmdExecutor.execute(new TestResponseRunner((YanQuMessage) msg, this.jobId));
            return;
        }
        if(msg instanceof BinaryWebSocketFrame){
            YanQuMessage message = new YanQuMessage();
            BinaryWebSocketFrame socketFrame = (BinaryWebSocketFrame)msg;
            try {
                message.read(socketFrame.content());
                testCmdExecutor.execute(new TestResponseRunner(message, this.jobId));
                //logger.info("JobClientHandler ....{}", message.getCode());
            }catch (Exception e){
                logger.error(e.getMessage(), e);
            }
            return;
        }else if(msg instanceof CloseWebSocketFrame) {
            //logger.info("JobClientHandler CloseWebSocketFrame");
            TestJob job = JobManager.getJobById(jobId);
            if(job != null){
                job.stop();
                JobManager.removeJob(jobId);
            }
        }
        //logger.info("JobClientHandler ....");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage(), cause);
    }
}
